package nj.yb.client;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.*;
import nj.yb.entity.message.ChatMessage;
import nj.yb.entity.request.*;
import nj.yb.entity.user.User;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class ChatClient {
    //当前用户信息
    private User currentUser;

    private ChatClientHandler chatClientHandler;

    Scanner scanner  = new Scanner(System.in);

    private static final long LOGIN_TIMEOUT = 10;
    private static final long REGISTER_TIMEOUT = 5000;

    private boolean isFirstHistoryRequest = true;


    public ChatClient(ChatClientHandler chatClientHandler) {
        this.chatClientHandler = chatClientHandler;
    }

    /**
     * 发送注册请求
     * @param channel
     */
    public void sendRegisterRequest(Channel channel) throws InterruptedException {
        String usrname = null;
        String nickname = null;
        String password = null;
        while(true){
            System.out.println("==============注册==============");
            System.out.println("在用户名处输入@exit可以退出注册");
            System.out.print("请输入用户名：");
            usrname = scanner.next();
            if(usrname.equals("@exit")){
                break;
            }
            System.out.print("请输入昵称：");
            nickname = scanner.next();
            System.out.print("请输入密码：");
            password = scanner.next();
            System.out.print("请确认密码：");
            String passwordConfirmation = scanner.next();
            if(! password.equals(passwordConfirmation)){
                System.out.println("两次密码输入不同！");
                continue;
            }
            //初始化同步信号量
            CountDownLatch registerLatch = new CountDownLatch(1);
            chatClientHandler.setRegisterLatch(registerLatch);


            AuthRequest request = new AuthRequest();
            request.setType(RequestType.REGISTER);
            request.setUsername(usrname);
            request.setPassword(password);
            request.setNickname(nickname);
            channel.writeAndFlush(JSON.toJSONString(request)+"\n");

            //阻塞等待响应
            boolean isTimeout = !registerLatch.await(REGISTER_TIMEOUT, TimeUnit.MILLISECONDS);

            //等待结果
            if (isTimeout) {
                System.out.println("网络超时，请检查网络连接！！！");
            }else if(chatClientHandler.isRegisterSuccess()){
                System.out.println("注册成功");
                break;
            }else{
                System.out.println("注册失败："+chatClientHandler.getRegisterFailReason());
            }

        }

    }


    /**
     * 发送登陆请求
     * @param channel
     */
    public boolean sendLoginRequest(Channel channel) throws InterruptedException {
        String username = null;
        String password = null;
        boolean flag = false;
        AuthRequest request = new AuthRequest();
        while(true) {
            //从用户获取输入
            System.out.println("=============登陆=============");
            System.out.print("请输入用户名：");
            username = scanner.next().trim();
            System.out.print("请输入密码：");
            password = scanner.next().trim();
            //初始化同步信号量
            CountDownLatch loginLatch = new CountDownLatch(1);
            chatClientHandler.setLoginLatch(loginLatch);

            //发送登录请求
            request.setType(RequestType.LOGIN);
            request.setUsername(username);
            request.setPassword(password);
            channel.writeAndFlush(JSON.toJSONString(request) + "\n");

            //阻塞等待响应
            boolean isTimeout = !loginLatch.await(LOGIN_TIMEOUT, TimeUnit.SECONDS);

            //等待结果
            if (isTimeout) {
                System.out.println("登录超时，请检查网络连接！！！");
            }else if(chatClientHandler.isLoginSuccess()){
                User loginUser = chatClientHandler.getLoginUser();
                currentUser = loginUser;
                System.out.printf("登陆成功！用户ID：%d,用户名：%s \n",loginUser.getId(),loginUser.getUsername());
                flag = true;
                break;
            }else{
                System.out.println("登录失败："+chatClientHandler.getLoginFailReason());
            }
        }
        return flag;
    }

    /**
     * 发送历史消息拉取请求
     * @param channel
     */
    public void sendHistoryRequest(Channel channel){
        String targetUsername = null;
        System.out.print("你要查找与谁的聊天记录，请输入用户名：");
        targetUsername = scanner.next();
        HistoryMsgRequest request = new HistoryMsgRequest();
        request.setUsername(currentUser.getUsername());
        request.setLimit(50);
        request.setTargetUser(targetUsername);
        channel.writeAndFlush(JSON.toJSONString(request)+"\n");


    }

    /**
     * 发送获取好友请求
     * @param channel
     */
    public void sendFriendListRequest(Channel channel){
        FriendListRequest request = new FriendListRequest();
        request.setUserId(currentUser.getId());
        channel.writeAndFlush(JSON.toJSONString(request)+"\n");
    }

    /**
     * 发送聊天的消息
     * @param channel
     * @param input
     */
    public void sendChatRequest(Channel channel,String input,String receiver){
        ChatMessage msg = new ChatMessage();
        msg.setMsgType(ChatMessage.TYPE_PRIVATE);
        msg.setReceiver(receiver);
        msg.setContent(input);
        msg.setSendTime(new Date());
        msg.setSender(currentUser.getUsername());
        msg.setRead(false);
        ChatRequest request = new ChatRequest(msg);

        channel.writeAndFlush(JSON.toJSONString(request)+"\n");
    }

    public void sendAddFriendRequest(Channel channel){
        System.out.println("请输入要添加的用户的用户名：");
        String targetUser = scanner.next();
        AddFriendRequest request = new AddFriendRequest();
        request.setUserId(currentUser.getId());
        request.setTargetUser(targetUser);

        //System.out.println(JSON.toJSONString(request)+"\n");
        channel.writeAndFlush(JSON.toJSONString(request)+"\n");
    }

    /**
     * 发送拉取未读消息的请求
     * @param channel
     * @param receiver
     */
    public void sendNotReadMessagesRequest(Channel channel,String receiver){
        NotReadMessagesRequest request = new NotReadMessagesRequest();
        request.setUsername(currentUser.getUsername());
        request.setTargetUser(receiver);

        channel.writeAndFlush(JSON.toJSONString(request)+"\n");
    }

    /**
     * 发送拉取群聊列表的请求
     * @param channel
     */
    public void sendGetGroupListRequest(Channel channel){
        GetGroupListRequest request = new GetGroupListRequest();
        request.setUsername(currentUser.getUsername());

        channel.writeAndFlush(JSON.toJSONString(request)+"\n");
    }

    /**
     * 发送加入群聊的请求
     * @param channel
     */
    public void sendJoinGroup(Channel channel){
        String username = currentUser.getUsername();
        System.out.print("请输入要加入的群聊名称：");
        String groupname = scanner.next();
        JoinGroupRequest request = new JoinGroupRequest();
        request.setUsername(username);
        request.setGroupname(groupname);

        channel.writeAndFlush(JSON.toJSONString(request)+"\n");
    }

    /**
     * 发送创建群聊的请求
     * @param channel
     */
    public void createGroup(Channel channel){

    }



}
